﻿CREATE PROCEDURE [dbo].[InventoryLinesUpdateEx]
(
	@DocId int,
	@PartyId int,
	@DocQntty int,
	@FactQntty int,
	@MD datetime,
	@MW varchar(128)
)
AS	
DECLARE @intDocTypeId int, @intGoodsDocLineId int, @intRowCount int
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intNextId int

SET NOCOUNT ON
IF (@DocId Is Null) OR (@DocQntty Is Null) OR (@FactQntty Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@DocQntty < 0) OR (@FactQntty < 0)
BEGIN
	SELECT @intErrCode = 2, 
	@strMsg = 'Количество должно быть больше или равно нулю!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intDocTypeId = DocTypeId FROM CA.Documents WHERE Id = @DocId

IF (@intDocTypeId <> 6)
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Неправильный тип документа!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

--проверить существование обновляемой записи
IF @PartyId IS NOT NULL
BEGIN
	IF NOT EXISTS ( SELECT Id FROM CD.InventoryLines WHERE DocId = @DocId AND PartyId = @PartyId )
	BEGIN
		SELECT @intErrCode = 4, 
		@strMsg = 'Не найдена партия с идентификатором ' + cast(@PartyId as varchar(20)) + ' !'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END
END

--EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT

BEGIN TRAN

IF (@PartyId Is Null)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 5, 
	@strMsg = 'Не указана партия!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SET NOCOUNT OFF;
UPDATE CD.InventoryLines 
SET [DocQntty]=@DocQntty, [FactQntty]=@FactQntty, [MD]=@MD, [MW]=@MW
WHERE DocId=@DocId AND PartyId=@PartyId

SELECT @intErrCode = @@error, @intRowCount = @@rowcount
IF @intErrCode <> 0 
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	RETURN @intErrCode
END
IF (@intRowCount <> 1)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 6, 
	@strMsg = 'Запись в таблице инвентаризации не обновлена!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END
	
COMMIT TRAN

SELECT Id, DocId, PartyId FROM CD.InventoryLines WHERE DocId=@DocId

RETURN 0